import 'dart:async';

import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:reabammendian/src/reabam/operation/bean/api_upload_order_task.dart';
import 'package:reabammendian/src/reabam/operation/bean/bean_retry_order.dart';
import 'package:reabammendian/src/reabam/operation/bean/h5_search_good.dart';
import 'package:reabammendian/src/reabam/operation/bean/h5_upload_order.dart';
import 'package:reabammendian/src/reabam/operation/rb_config.dart';
import 'package:reabammendian/src/reabam/operation/rb_api.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_json.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:xsdk_flutter_plugin/xsdk_flutter_plugin.dart';

// 通过 `flutter pub run build_runner build`  生成的objectbox.g.dart
import '../../../../objectbox.g.dart';
import 'models.dart';
import 'models_upload_order_task.dart';


typedef XFunctionObjectBoxCallback = void Function(String json);

/*
flutter pub run build_runner build
 */
class XObjectBoxUtils {
  //在生成的objectbox.g.dart内
  static Store? store;

  static Box<BeanOfflineDBGood>? goodBox;
  static Box<BeanOfflineDBGoodSpec>? goodSpecBox;
  static Box<BeanOfflineDBOrder>? orderBox;
  static Box<BeanOfflineDBPendingOrder>? pendingOrderBox;
  static Box<TestDBItem>? testItemBox;

  static Box<BeanUploadOrderTask>? uploadOrderTaskBox;
  static Box<BeanUploadOrderDetail>? uploadOrderDetailBox;
  static Box<BeanCompleteUploadOrder>? uploadOrderBakBox;
  static Box<BeanUploadOrderTaskBak>? uploadOrderTaskBakBox;
  static Box<BeanUploadOrderShoppingCart>? uploadOrderShoppingCartBox;

  XObjectBoxUtils._create() {
    // 初始化各个实体类对应box,等同: Box<BeanOfflineDBGood>(store!);
    goodBox=store?.box<BeanOfflineDBGood>();
    goodSpecBox=store?.box<BeanOfflineDBGoodSpec>();
    orderBox=store?.box<BeanOfflineDBOrder>();
    pendingOrderBox=store?.box<BeanOfflineDBPendingOrder>();
    testItemBox=store?.box<TestDBItem>();
    uploadOrderTaskBox=store?.box<BeanUploadOrderTask>();
    uploadOrderDetailBox=store?.box<BeanUploadOrderDetail>();
    uploadOrderBakBox=store?.box<BeanCompleteUploadOrder>();
    uploadOrderTaskBakBox=store?.box<BeanUploadOrderTaskBak>();
    uploadOrderShoppingCartBox=store?.box<BeanUploadOrderShoppingCart>();
  }

  /*
  1.初始化,可在app中初始化,或者在登录后调用接口获得对应的id使用不同的数据库
  //已在app中初始化WidgetsFlutterBinding.ensureInitialized();
  如:
  await XObjectBoxUtils.create(dbname);
   */
  static Future<XObjectBoxUtils> create(String dbName) async {

    final docsDir = await getApplicationDocumentsDirectory();
    //在生成的objectbox.g.dart内
    store = await openStore(
      directory: p.join(docsDir.path, dbName),
      macosApplicationGroup: 'FGDTDLOBXDJ.demo',//用于macOS沙箱
    );
    return XObjectBoxUtils._create();
  }


  ///////////////////////////////////////////////////////////////////////

  static void saveBeanUploadOrderTask(BeanUploadOrderTask item){
    uploadOrderTaskBox!.putAsync(item);
  }
  static void saveBeanOfflineDBGood(BeanOfflineDBGood item){
    goodBox!.put(item);
  }
  static void saveBeanOfflineDBGoodSpec(BeanOfflineDBGoodSpec item){
    goodSpecBox!.put(item);
  }

  static BeanOfflineDBGood? getBeanOfflineDBGoodById(int id) {
    return goodBox!.get(id);
  }


  static void getBeanOfflineDBGoodList(
      {
        required int pageIndex,
        required int pageSize,
        String? fCode,
        String? keyword,
        required XFunctionObjectBoxCallback callback
      }
      ) {

    Future((){
      ItemListResponse response =ItemListResponse();

      try{

        if (pageIndex<0||pageSize<=0){
          response.code="-1";
          callback(XJsonUtils.obj2Json(response));
          return;
        }

        //总页数
        int pageCount=0;
        //总商品数
        int totalCount=0;

        List<BeanOfflineDBGood> list=[];


        if (XStringUtils.isEmpty(keyword)){

          if (XStringUtils.isEmpty(fCode)){

            //计算分页,总商品数
            totalCount=goodBox!.count()??0;
            if (totalCount/pageSize==0){
              pageCount=1;
            }else{
              pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
            }
            //偏离数=当前页数(第一页从1开始)*每页数量
            int offset=(pageIndex-1)*pageSize;

            //全部分类
            Query<BeanOfflineDBGood> query =goodBox!.query().order(BeanOfflineDBGood_.id).build();
            query.limit=pageSize;
            query.offset=offset;
            list = query.find();
            query.close();

          }else{
            //按分类  同一张分类表支持多层,用contains,不用equal
            Query<BeanOfflineDBGood> query =goodBox!
                .query(BeanOfflineDBGood_.itemTypefCode.contains(fCode!))
                .order(BeanOfflineDBGood_.id).build();

            //计算分页,总商品数
            totalCount=query.count();
            if (totalCount/pageSize==0){
              pageCount=1;
            }else{
              pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
            }
            //偏离数=当前页数(第一页从1开始)*每页数量
            int offset=(pageIndex-1)*pageSize;

            query.limit=pageSize;
            query.offset=offset;
            list = query.find();
            query.close();

          }

        }else{
          //全部分类
          Query<BeanOfflineDBGood> query =goodBox!
              .query(
              BeanOfflineDBGood_.itemName.contains(keyword!)
                  .or(BeanOfflineDBGood_.skuBarcode.contains(keyword!)
                  .or(BeanOfflineDBGood_.itemCode.contains(keyword!)
                  .or(BeanOfflineDBGood_.pinyin.contains(keyword!)
              ))))
              .order(BeanOfflineDBGood_.id).build();

          //计算分页,总商品数
          totalCount=query.count();
          if (totalCount/pageSize==0){
            pageCount=1;
          }else{
            pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
          }
          //偏离数=当前页数(第一页从1开始)*每页数量
          int offset=(pageIndex-1)*pageSize;

          query.limit=pageSize;
          query.offset=offset;
          list = query.find();
          query.close();
        }

        //
        List<Map<String,dynamic>> h5JsonList=[];

        for (BeanOfflineDBGood sItem in list){
          Map<String,dynamic> m=XJsonUtils.json2Map(sItem.json);
          //XLogUtils.printLog('-------m=${m.toString()}');
          h5JsonList.add(m);
        }

        response.code="200";
        response.msg='1213';
        response.PageIndex=pageIndex;
        response.PageCount=pageCount;
        response.totalCount=totalCount;
        response.items=h5JsonList;

        callback(XJsonUtils.obj2Json(response));

      }catch(e){
        XLogUtils.printLog('$e');
        response.code="-1";
        callback(XJsonUtils.obj2Json(response));
      }
    });

  }


//查找规格,第一页从1开始
  static void getSpecItemList(
      List<String>? specIds,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ItemListResponse response =ItemListResponse();

      try{

        if (specIds==null||specIds.length==0){
          response.code="-1";
          callback(XJsonUtils.obj2Json(response));
          return;
        }

        //
        Query<BeanOfflineDBGoodSpec>? query;
        Condition<BeanOfflineDBGoodSpec>? condition;

        for (int i=0;i<specIds!.length;i++){
          if (i==0){
            condition=BeanOfflineDBGoodSpec_.specId.equals(specIds[0]);
          }else{
            //叠加
            condition!.or(BeanOfflineDBGoodSpec_.specId.equals(specIds[0]));
          }

          if (i==(specIds.length-1)){
            //最后叠加
            query=goodSpecBox!.query(condition).order(BeanOfflineDBGoodSpec_.id)
                .build();
          }

        }

        List<BeanOfflineDBGoodSpec> list = query!.find();
        query.close();

        XLogUtils.printLog('---规格list=${XJsonUtils.obj2Json(list)}');

        //
        List<Map<String,dynamic>> h5JsonList=[];

        for (BeanOfflineDBGoodSpec sItem in list){
          Map<String,dynamic> m=XJsonUtils.json2Map(sItem.json);
          //XLogUtils.printLog('-------m=${m.toString()}');
          h5JsonList.add(m);
        }

        response.code="200";
        response.PageIndex=1;
        response.PageCount=list.length;
        response.totalCount=1;
        response.items=h5JsonList;

        callback(XJsonUtils.obj2Json(response));

      }catch (e){
        XLogUtils.printLog('---getSpecItemList报错: $e');
        response.code='-1';
        callback(XJsonUtils.obj2Json(response));
      }

    });



  }


  //订单上传任务///////////////////////////////////////////////////////////////////////////

  static String _getAliyunLogKey_UploadOrder(String? orderNo){
    String companyId=XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
    return '上传, companyId=$companyId, orderNo= $orderNo';
  }

  //保存订单上传任务ok
  static void saveUploadOrderTask(BeanH5UploadOrderTask itemH5,XFunctionObjectBoxCallback callback){

    Future((){

      try{
        BeanUploadOrderTask item=BeanUploadOrderTask();
        item.createDate=XDateUtils.getCurrentTime_String(format: XDateUtils.formatTimeDefault2);
        item.createDateLong=XDateUtils.getCurrentTime_ms();
        item.functionTypes='${itemH5.functionTypes}';
        item.orderType='${itemH5.orderType}';
        item.member=itemH5.member;
        item.phone=itemH5.phone;
        item.shoppingGuide=itemH5.shoppingGuide;
        item.cashier=itemH5.cashier;
        item.orderStatus='${itemH5.orderStatus}';
        item.orderStatusName=itemH5.orderStatusName;
        item.payStatus=itemH5.payStatus;
        item.payStatusName='${itemH5.payStatusName}';
        item.typeCode='${itemH5.typeCode}';
        item.fastOrderNo=itemH5.fastOrderNo;
        item.pushVersion=itemH5.pushVersion;
        item.pushClient=itemH5.pushClient;
        //对象转string保存
        item.pushJson=XJsonUtils.obj2Json(itemH5.pushJson);

        //
        if ('1'==item.typeCode){
          //新增订单,保存到订单记录表
          XLogUtils.printLog('---记录新增订单');
          List<String> payList=[];
          item.payListJson=XJsonUtils.obj2Json(payList);
          //1.保存到新增订单表
          String orderJson=XJsonUtils.obj2Json(item);
          BeanUploadOrderDetail orderItem= BeanUploadOrderDetail.fromJson(XJsonUtils.json2Map(orderJson));
          orderItem.id=0;
          //判断是否重复单号再存入...
          uploadOrderDetailBox!.put(orderItem);

          //2.保存订单记录备份
          BeanCompleteUploadOrder order_bak= BeanCompleteUploadOrder();
          order_bak.fastOrderNo=item.fastOrderNo;
          order_bak.createDate=item.createDate;
          order_bak.createDateLong=item.createDateLong;
          uploadOrderBakBox!.put(order_bak);

          //3.保存到任务队列
          uploadOrderTaskBox!.put(item);

          //日志
          XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(item.fastOrderNo),'新增订单成功!');
          //通知h5
          callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "200",msg: "成功添加到任务队列")));

        }else if ('2'==item.typeCode){
          //支付
          XLogUtils.printLog('---记录每笔支付');
          //1.查找订单
          Query<BeanUploadOrderDetail> query=uploadOrderDetailBox!.query(
              BeanUploadOrderDetail_.fastOrderNo.equals(item.fastOrderNo!)
          ).build();
          List<BeanUploadOrderDetail> list=query.find();
          query.close();
          if (list.length!=0){
            //存在,则有效
            //1.修改状态
            BeanUploadOrderDetail orderItem=list[0];
            orderItem.orderStatus=item.orderStatus;
            orderItem.orderStatusName=item.orderStatusName;
            orderItem.payStatus=item.payStatus;
            orderItem.payStatusName=item.payStatusName;
            //重置为业务未追平
            orderItem.businessSuccess=false;

            //插入每笔支付
            String? payListJson=orderItem.payListJson;
            List<dynamic> payList=[];
            if(!XStringUtils.isEmpty(payListJson)){
              payList=XJsonUtils.json2List(payListJson);
            }
            payList.add(itemH5.pushJson);
            orderItem.payListJson=XJsonUtils.obj2Json(payList);
            //更新记录数据
            uploadOrderDetailBox!.put(orderItem);
            XLogUtils.printLog('---修改订单状态成功! 插入支付记录成功!');

            //2.保存到任务队列
            uploadOrderTaskBox!.put(item);

            //日志
            XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(item.fastOrderNo),'插入1笔支付成功!');
            //通知h5
            callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "200",msg: "成功添加到任务队列")));

          }else{
            //订单记录不存在,不添加到任务队列
            XLogUtils.printLog('---订单记录不存在,此任务不能添加到任务队列!');
            //日志
            XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(item.fastOrderNo),'订单记录不存在,此任务不能添加到任务队列!');
            //通知h5
            callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "-1",msg: "订单记录不存在,此任务不能添加到任务队列")));

          }

        }else{
          //其他任务:取消,退货等
          XLogUtils.printLog('---任务typeCode非1和2');

          //查找订单
          Query<BeanUploadOrderDetail> query=uploadOrderDetailBox!.query(
              BeanUploadOrderDetail_.fastOrderNo.equals(item.fastOrderNo!)
          ).build();
          List<BeanUploadOrderDetail> list=query.find();
          query.close();
          if (list.length!=0){
            //存在,则有效
            //1.修改状态
            BeanUploadOrderDetail orderItem=list[0];
            orderItem.orderStatus=item.orderStatus;
            orderItem.orderStatusName=item.orderStatusName;
            orderItem.payStatus=item.payStatus;
            orderItem.payStatusName=item.payStatusName;
            //重置为业务未追平
            orderItem.businessSuccess=false;
            //
            uploadOrderDetailBox!.put(orderItem);
            XLogUtils.printLog('---修改订单状态成功');

            //2.保存到任务队列
            uploadOrderTaskBox!.put(item);

            //日志
            XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(item.fastOrderNo),'添加其他任务成功!');
            //通知h5
            callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "200",msg: "成功添加到任务队列")));

          }else{
            //订单记录不存在,不添加到任务队列
            XLogUtils.printLog('---订单记录不存在,此任务不能添加到任务队列!');
            //日志
            XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(item.fastOrderNo),'订单记录不存在,此任务不能添加到任务队列');
            //通知h5
            callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "-1",msg: "订单记录不存在,此任务不能添加到任务队列")));

          }

        }

        //保存任务记录备份
        //L.sdk("---保存taskId="+item.taskId);
        String taskJson=XJsonUtils.obj2Json(item);
        BeanUploadOrderTaskBak task_bak= BeanUploadOrderTaskBak.fromJson(XJsonUtils.json2Map(taskJson));
        task_bak.id=0;
        task_bak.taskId=item.id;
        uploadOrderTaskBakBox!.put(task_bak);

      }catch (e){
        XLogUtils.printLog('---saveUploadOrderTask报错: $e');
        //通知h5
        callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "-1",msg: "添加到任务队列出错!")));

      }

    });


  }

  //保存订单购物车信息ok
  static void saveOrderShoppingcart(BeanH5UploadOrderTask itemH5,XFunctionObjectBoxCallback callback){

    Future((){
      try{
        //订单的购物车信息,保存到购物车临时表
        BeanUploadOrderShoppingCart shoppingcartItem=BeanUploadOrderShoppingCart();
        shoppingcartItem.fastOrderNo=itemH5.fastOrderNo;
        shoppingcartItem.pushJson=XJsonUtils.obj2Json(itemH5.pushJson);
        shoppingcartItem.createDate=XDateUtils.getCurrentTime_String(format: XDateUtils.formatTimeDefault2);
        shoppingcartItem.createDateLong=XDateUtils.getCurrentTime_ms();
        //保存
        uploadOrderShoppingCartBox!.put(shoppingcartItem);
        //
        callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "200",msg: "保存购物车成功!")));

      }catch (e){
        XLogUtils.printLog('---saveOrderShoppingcart报错: $e');
        //
        callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response(code: "-1",msg: "保存购物车出错!")));
      }
    });

  }

  //获得订单购物车 ok
  static void getOrderShoppingcart(String orderNo, XFunctionObjectBoxCallback callback){
    Future((){

      try{
        BeanUploadOrderH5Response2 response =BeanUploadOrderH5Response2();

        Query<BeanUploadOrderShoppingCart> query=
        uploadOrderShoppingCartBox!.query(BeanUploadOrderShoppingCart_.fastOrderNo.equals(orderNo))
            .order(BeanUploadOrderShoppingCart_.id,flags:Order.descending)
            .build();
        List<BeanUploadOrderShoppingCart> list=query.find();
        query.close();
        if (list.length==0){
          response.code="-1";
          response.msg="不存在该订单的购物车记录";
        }else{
          response.code="200";
          response.msg="成功";
          BeanUploadOrderShoppingCart item=list[0];

          Map<String, dynamic> m=XJsonUtils.json2Map(item.pushJson);
          m['createDate']=item.createDate;
          m['fastOrderNo']=item.fastOrderNo;
          response.orderId=item.fastOrderNo;
          response.data=m;
        }

        String json= XJsonUtils.obj2Json(response);
        //
        callback(json);
      }catch (e){
        XLogUtils.printLog('---getOrderShoppingcart报错: $e');
        //
        callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response2(code: "-1",msg: "获得购物车出错!")));
      }

    });

  }



  //刷新订单,检测是否已追平 ok
  static void retryOrder(String orderNo,XFunctionObjectBoxCallback callback){
    Future(() async{
      try{
        //1.检测本地未追平的单任务是否存在
        List<BeanUploadOrderTask> list_task=uploadOrderTaskBox!.getAll();
        bool isHas=false;
        if (list_task.length!=0){
          for (BeanUploadOrderTask taskItem in list_task){
            if (taskItem.fastOrderNo==orderNo){
              isHas=true;
              break;
            }
          }
        }

        if (isHas){
          //还存在该单的任务未上传,则没追平
          //通知完成更新
          callback(XJsonUtils.obj2Json(BeanRetryUploadOrderH5Response(code: "200",msg: "此单还有未上传任务!",retrySuccess: false)));
        }else {
          //不存在该单未上传任务,则请求api重试
          List<String> fastOrderNos =[];
          fastOrderNos.add(orderNo);
          Response_retry_pos_order? response = await RBApi.retryPosOrder(
              fastOrderNos:fastOrderNos,
              groupId:XSharePreferencesUtils.getString(RBConfigs.SP_groupId)
          );

          String? code;
          String? msg;
          bool retrySuccess=false;

          if (response != null) {
            code=response.code;
            msg=response.msg;

            List<BeanRetryData>? data = response.data;
            if (data != null && data.length != 0) {
              BeanRetryData retryData = data[0];
              msg = retryData.retryResult;

              if (retryData.retrySuccess) {
                //
                retrySuccess = true;
                //追平,删除本地订单
                Query<BeanUploadOrderDetail> query = uploadOrderDetailBox!.query(BeanUploadOrderDetail_.fastOrderNo.equals(orderNo))
                    .build();
                List<BeanUploadOrderDetail> list2 = query.find();
                query.close();
                List<int> ids=[];
                for(BeanUploadOrderDetail detail in list2){
                  ids.add(detail.id);
                }
                uploadOrderDetailBox!.removeMany(ids);

                //日志
                XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(orderNo),'重试(api)已追平删除本地订单!, response=${XJsonUtils.obj2Json(response)}');
              }
            }
          } else {
            code = "-1";
            msg='刷新订单出错!';
          }

          //通知完成更新
          callback(XJsonUtils.obj2Json(BeanRetryUploadOrderH5Response(code: code,msg: msg,retrySuccess: retrySuccess)));
        }
      }catch (e){
        XLogUtils.printLog('---retryOrder报错: $e');
        //
        callback(XJsonUtils.obj2Json(BeanRetryUploadOrderH5Response(code: "-1",msg: "刷新订单出错!",retrySuccess: false)));
      }

    });


  }


  //查找本地未追平订单(触发检测所有订单是否已追平) ok
  static void getUploadOrderList(BeanH5RequestPageLocalOrder request, XFunctionObjectBoxCallback callback){
    Future((){
      try{
        //1.触发检测所有订单是否已追平(已追平则删除)
        checkAndDeleteUploadOrder();

        //2.查找本地订单(未追平的订单)
        String json= _findUploadOrderList(request);
        callback(json);

      }catch (e){
        XLogUtils.printLog('---getUploadOrderList报错: $e');
      }
    });
  }


  //检测本地订单是否已追平(已追平则删除) ok
  static void checkAndDeleteUploadOrder() async {
    try{
      //1.由于已在添加订单任务时,已重置业务状态为false,则查出不存在业务异常的单号即可删除
      List<BeanUploadOrderDetail> recordOrderList=uploadOrderDetailBox!.getAll();
      recordOrderList.removeWhere((BeanUploadOrderDetail order){
        if (order.businessSuccess){
          //不存在业务异常的单号,可以删除
          uploadOrderDetailBox!.remove(order.id);
          //日志
          XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(order.fastOrderNo),'检查(本地)已追平删除本地订单!');
          return true;
        }else{
          return false;
        }
      });

      //2.剩余业务异常的订单调用api检测是否已追平
      XLogUtils.printLog('---检测本地订单是否已追平,存在业务异常订单:${recordOrderList.length}');
      if (recordOrderList.length==0){
        //所有订单已追平
        return;
      }
      List<String> fastOrderNos=[];
      for (BeanUploadOrderDetail order in recordOrderList){
        fastOrderNos.add(order.fastOrderNo!);
      }
      Response_check_order? response= await RBApi.checkOrderBusinessStatus(
          fastOrderNos: fastOrderNos
      );

      if (response!=null){
        List<BeanCheckOrderData>? data=response.data;
        if (data!=null){
          for (BeanCheckOrderData iitem in data){
            if (iitem.businessSuccess){
              //api业务实际已追平,删除订单

              recordOrderList.removeWhere((BeanUploadOrderDetail order){
                if (iitem.fastOrderNo==order.fastOrderNo){
                  uploadOrderDetailBox!.remove(order.id);
                  //日志
                  XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(order.fastOrderNo),'检查(api)已追平删除本地订单!');
                  return true;
                }else{
                  return false;
                }
              });
            }
          }
        }
      }
      XLogUtils.printLog('---检测本地订单是否已追平处理完毕,剩余未追平单: ${recordOrderList.length}, ${uploadOrderDetailBox!.count()}');
    }catch (e){
      XLogUtils.printLog('---checkAndDeleteUploadOrder报错:$e');
    }
  }


  //查找本地订单(未追平的订单)ok
  static String _findUploadOrderList(BeanH5RequestPageLocalOrder request){

    BeanUploadOrderH5Response3 response =BeanUploadOrderH5Response3();

    try{

      int pageIndex=request.pageIndex;
      int pageSize=request.pageSize;
      //String? keyword=request.sword;

      if (pageIndex<=0||pageSize<=0){
        response.code="-1";
        return XJsonUtils.obj2Json(response);
      }
      //


      //总商品数
      int totalCount=uploadOrderDetailBox!.count();
      XLogUtils.printLog('---UploadOrderList all size=$totalCount');

      //总页数
      int pageCount=0;
      if (totalCount/pageSize==0){
        pageCount=1;
      }else{
        pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
      }
      //偏离数=当前页数(第一页从1开始)*每页数量
      int offset=(pageIndex-1)*pageSize;


      List<BeanUploadOrderDetail> list=[];

      Query<BeanUploadOrderDetail> query=uploadOrderDetailBox!.query()
          .order(BeanUploadOrderDetail_.id,flags: Order.descending)
          .build();
      query.limit=pageSize;
      query.offset=offset;
      list = query.find();
      query.close();

      //
      List<dynamic> pushJsonList=[];
      for (BeanUploadOrderDetail sItem in list){
        Map<String,dynamic> m=XJsonUtils.json2Map(sItem.pushJson);
        List<dynamic> payJsonList=XJsonUtils.json2List(sItem.payListJson);
        m['allPayList']=payJsonList;
        m['orderStatus']=sItem.orderStatus;
        m['orderStatusName']=sItem.orderStatusName;
        m['payStatus']=sItem.payStatus;
        m['payStatusName']=sItem.payStatusName;
        m['orderId']=sItem.orderId;
        m['orderMsg']=sItem.orderMsg;
        m['synSuccess']=sItem.synSuccess;
        m['businessSuccess']=sItem.businessSuccess;
        m['createDate']=sItem.createDate;
        pushJsonList.add(m);
      }

      response.code="200";
      response.PageIndex=pageIndex;
      response.PageCount=pageCount;
      response.totalCount=totalCount;
      response.items=pushJsonList;

      XLogUtils.printLog('---未追平订单h5JsonList=${list.length}');
      XLogUtils.printLog('----未追平订单h5JsonList:${XJsonUtils.obj2Json(response)}');

    }catch ( e){
      XLogUtils.printLog('---findUploadOrderList报错:$e');
    }

    return XJsonUtils.obj2Json(response);

  }


  //删除今天以前的购物车信息
  static void removeOldOrderShoppingcart(){
    try{

      XLogUtils.printLog('---自动清除今天以前所有订单购物车!');

      //今天0点时间
      int longtime=XDateUtils.getToday0HourTime_ms();

      Query<BeanUploadOrderShoppingCart> query=uploadOrderShoppingCartBox!.query(BeanUploadOrderShoppingCart_.createDateLong.lessThan(longtime))
          .build();
      List<BeanUploadOrderShoppingCart> list=query.find();
      query.close();
      //删除
      List<int> ids=[];
      for(BeanUploadOrderShoppingCart shoppingCart in list){
        ids.add(shoppingCart.id);
      }
      if(ids.length!=0){
        uploadOrderShoppingCartBox!.removeMany(ids);
      }

    }catch (e){
      XLogUtils.printLog('---removeOldOrderShoppingcart报错: $e');
    }

  }

  //删除一个月前的订单备份上传任务
  static void remove1MonthAgoOrderTaskBak(){
    try{
      XLogUtils.printLog('---自动清除1个月前的所有备份订单任务!');

      //一个月前时间
      int longtime=XDateUtils.get1MonthAgoTime_ms();

      Query<BeanUploadOrderTaskBak> query=uploadOrderTaskBakBox!.query(BeanUploadOrderTaskBak_.createDateLong.lessThan(longtime))
          .build();
      List<BeanUploadOrderTaskBak> list=query.find();
      query.close();
      //删除
      List<int> ids=[];
      for(BeanUploadOrderTaskBak task in list){
        ids.add(task.id);
      }
      if(ids.length!=0){
        uploadOrderTaskBakBox!.removeMany(ids);
      }

    }catch (e){
      XLogUtils.printLog('---remove1MonthAgoOrderTaskBak报错: $e');
    }

  }

  //删除一个月前的备份订单
  static void remove1MonthAgoOrderBak(){
    try{
      XLogUtils.printLog('---自动清除1个月前的所有备份订单!');

      //一个月前时间
      int longtime=XDateUtils.get1MonthAgoTime_ms();

      Query<BeanCompleteUploadOrder> query=uploadOrderBakBox!.query(BeanCompleteUploadOrder_.createDateLong.lessThan(longtime))
          .build();
      List<BeanCompleteUploadOrder> list=query.find();
      query.close();
      //删除
      List<int> ids=[];
      for(BeanCompleteUploadOrder task in list){
        ids.add(task.id);
      }
      if(ids.length!=0){
        uploadOrderBakBox!.removeMany(ids);
      }

    }catch (e){
      XLogUtils.printLog('---remove1MonthAgoOrderBak报错: $e');
    }

  }


  //循环处理订单任务上传ok
  static void handleUploadOrderTask(XFunctionObjectBoxCallback callback) async{
    try{
      //L.sdk("---待上传任务数量:"+box.count());
      Query<BeanUploadOrderTask> query=uploadOrderTaskBox!.query()
          .order(BeanUploadOrderTask_.id)
          .build();
      query.limit=1;
      query.offset=0;
      List<BeanUploadOrderTask> list=query.find();

      if (list.length==0){
        //没有待上传任务
        callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response4('-123',"没有可上传的订单任务",'0',null)));
      }else {
        //存在待上传任务
        //上传成功则可删除(业务异常订单则后期再调检测接口更新追平状态)
        BeanUploadOrderTask waitUploadItem = list[0];
        //上传任务
        Response_upload_order? response = await RBApi.uploadOrderTask(
            taskId:'${waitUploadItem.id}',
            typeCode:waitUploadItem.typeCode,
            fastOrderNo:waitUploadItem.fastOrderNo,
            pushJson:waitUploadItem.pushJson,
            pushVersion:waitUploadItem.pushVersion,
            pushClient:waitUploadItem.pushClient
        );

        //L.sdk("---上传任务res="+XJsonUtils.obj2String(response));

        String msg = "同步任务失败";
        String orderId = "";
        String? typeCode = waitUploadItem.typeCode;
        String? fastOrderNo = waitUploadItem.fastOrderNo;
        bool synSuccess = false;
        bool businessSuccess = false;

        if (response != null && response.data != null) {
          //成功
          synSuccess = response.data!.synSuccess;
          businessSuccess = response.data!.businessSuccess;
          orderId = response.data!.orderId??'';
          msg = response.data!.businessErrorMsg??'';

        }

        //日志
        XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(waitUploadItem.fastOrderNo),'typeCode=${waitUploadItem.typeCode}, 订单上传结果: ${XJsonUtils.obj2Json(response)}, 上传参数=${waitUploadItem.pushJson}');


        if (synSuccess) {
          XLogUtils.printLog('---同步上传成功,删除队列任务,更新订单追平状态');

          //查找订单,更新追平状态
          Query<BeanUploadOrderDetail> query2 = uploadOrderDetailBox!.query(BeanUploadOrderDetail_.fastOrderNo.equals(waitUploadItem.fastOrderNo!))
              .build();
          List<BeanUploadOrderDetail> list2 = query2.find();
          //防止重复单号情况
          for (BeanUploadOrderDetail orderItem in list2) {
            orderItem.synSuccess = synSuccess;
            orderItem.businessSuccess = businessSuccess;
            orderItem.orderId = orderId;
            //当前任务的业务异常且当前错误信息为空的时候,保留上一条任务消息,不做更新
            if (!businessSuccess && !XStringUtils.isEmpty(msg)) {
              orderItem.orderMsg = msg;
            }
            uploadOrderDetailBox!.put(orderItem);
          }

          //删除任务队列
          uploadOrderTaskBox!.remove(waitUploadItem.id);
          callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response4('200', msg, typeCode, fastOrderNo)));

          //日志
          XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(waitUploadItem.fastOrderNo),'上传任务成功,删除任务!typeCode= ${waitUploadItem.typeCode}');


        } else {
          XLogUtils.printLog('---同步上传失败,保留任务');
          waitUploadItem.orderMsg = msg;
          uploadOrderTaskBox!.put(waitUploadItem);

          callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response4('-1', msg, typeCode, fastOrderNo)));

          //日志
          XAliyunUtils.sendLog(_getAliyunLogKey_UploadOrder(waitUploadItem.fastOrderNo),'上传任务失败,保留任务!typeCode= ${waitUploadItem.typeCode}');

        }
      }
    }catch (e){
      XLogUtils.printLog('---getUploadOrderTaskHandle报错: $e');
      callback(XJsonUtils.obj2Json(BeanUploadOrderH5Response4('-1', '$e', '', '')));
    }

  }


  //极速版1.0////////////////////////////////////////////////////
  //保存离线订单
  static void saveOfflineOrder(BeanOfflineDBOrder item){
    orderBox!.putAsync(item);
  }
  static void delOfflineOrder(int id){
    orderBox!.removeAsync(id);
  }
  static void savePendingOrder(BeanOfflineDBPendingOrder item){
    pendingOrderBox!.putAsync(item);
  }
  static void delPendingOrder(int id){
    pendingOrderBox!.removeAsync(id);
  }
  static void delAllPendingOrder(){
    pendingOrderBox!.removeAllAsync();
  }
  static int getPendingOrderTotalCount(){
    return pendingOrderBox!.count();
  }

  //获得挂单列表ok
  static void getOfflinePendingOrderList(int pageIndex,int pageSize,XFunctionObjectBoxCallback callback){

    Future((){
      BeanUploadOrderH5Response3 response =BeanUploadOrderH5Response3();

      try{

        if (pageIndex<=0||pageSize<=0){
          response.code="-1";
          callback(XJsonUtils.obj2Json(response));
        }
        //

        response.code='200';

        //总商品数
        int totalCount=pendingOrderBox!.count();

        //总页数
        int pageCount=0;
        if (totalCount/pageSize==0){
          pageCount=1;
        }else{
          pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
        }
        //偏离数=当前页数(第一页从1开始)*每页数量
        int offset=(pageIndex-1)*pageSize;

        List<BeanOfflineDBPendingOrder> list=[];

        Query<BeanOfflineDBPendingOrder> query=pendingOrderBox!.query()
            .order(BeanOfflineDBPendingOrder_.id,flags: Order.descending)
            .build();
        query.limit=pageSize;
        query.offset=offset;
        list = query.find();
        query.close();

        //
        List<dynamic> pushJsonList=[];
        for (BeanOfflineDBPendingOrder sItem in list){
          Map<String,dynamic> mapItem=XJsonUtils.json2Map(sItem.json);

          Map<String, dynamic> m={};
          m['longId']=sItem.id;
          m['serialNumber']=sItem.serialNumber;
          m['creatDate']=sItem.creatDate;
          m['totalMoney']=sItem.totalMoney;
          m['json']=mapItem;

          pushJsonList.add(m);
        }

        response.code="200";
        response.PageIndex=pageIndex;
        response.PageCount=pageCount;
        response.totalCount=totalCount;
        response.items=pushJsonList;

        XLogUtils.printLog('---挂单列表,size=${list.length}');

        callback(XJsonUtils.obj2Json(response));

      }catch ( e){
        XLogUtils.printLog('---getOfflinePendingOrderList报错:$e');
        callback(XJsonUtils.obj2Json(response));
      }

    });



  }
  //获得下单收银订单列表ok
  static void getOfflineOrderList(
      int pageIndex,
      int pageSize,
      String? keyword,
      XFunctionObjectBoxCallback callback){

    Future((){
      BeanUploadOrderH5Response3 response =BeanUploadOrderH5Response3();

      try{

        if (pageIndex<=0||pageSize<=0){
          response.code="-1";
          callback(XJsonUtils.obj2Json(response));
        }
        //

        response.code='200';

        //总商品数
        int totalCount=orderBox!.count();

        //总页数
        int pageCount=0;
        if (totalCount/pageSize==0){
          pageCount=1;
        }else{
          pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
        }
        //偏离数=当前页数(第一页从1开始)*每页数量
        int offset=(pageIndex-1)*pageSize;

        List<BeanOfflineDBOrder> list=[];

        if (XStringUtils.isEmpty(keyword)){
          //全部
          Query<BeanOfflineDBOrder> query=orderBox!.query()
              .order(BeanOfflineDBOrder_.id,flags: Order.descending)
              .build();
          query.limit=pageSize;
          query.offset=offset;
          list = query.find();
          query.close();
        }else{
          //按keyword
          Query<BeanOfflineDBOrder> query=orderBox!.query(BeanOfflineDBOrder_.orderNo.equals(keyword!))
              .order(BeanOfflineDBOrder_.id,flags: Order.descending)
              .build();
          query.limit=pageSize;
          query.offset=offset;
          list = query.find();
          query.close();
        }

        //
        List<dynamic> pushJsonList=[];
        for (BeanOfflineDBOrder sItem in list){
          Map<String,dynamic> mapItem=XJsonUtils.json2Map(sItem.json);

          Map<String, dynamic> m={};
          m['longId']=sItem.id;
          m['orderId']=sItem.orderId;
          m['orderNo']=sItem.orderNo;
          m['orderDate']=sItem.orderDate;
          m['json']=mapItem;

          pushJsonList.add(m);
        }

        response.code="200";
        response.PageIndex=pageIndex;
        response.PageCount=pageCount;
        response.totalCount=totalCount;
        response.items=pushJsonList;

        XLogUtils.printLog('---订单列表,size=${list.length}');

        callback(XJsonUtils.obj2Json(response));

      }catch ( e){
        XLogUtils.printLog('---getOfflinePendingOrderList报错:$e');
        callback(XJsonUtils.obj2Json(response));
      }

    });



  }

/////////////////////////////////////////////////////////////////////////////
//test
  static void saveTestDBItem(TestDBItem item){
    testItemBox!.putAsync(item);
  }
  static void saveTestDBList(List<TestDBItem> items){
    testItemBox!.putMany(items);
  }

  static void delTestDBItem(int id) {
    testItemBox!.remove(id);
  }
  static void delTestDBItemList(List<int> ids) {
    testItemBox!.removeMany(ids);
  }
  static void delALlTestDBItems() {
    testItemBox!.removeAll();
  }

  static TestDBItem? getTestDBItemById(int id) {
    return testItemBox!.get(id);
  }
  static List<TestDBItem>? getAllTestDBItems() {
    return testItemBox!.getAll();
  }

  static List<TestDBItem>? getTestDBItems() {
    final query =(testItemBox!.query(TestDBItem_.name.equals('Tom')).order(TestDBItem_.name)).build();
    final results = query.find();
    query.close();
    return results;
  }



}